//
//  Status.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/25.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit

class Status: NSObject {
    // 微博 ID
    var id : Int64 = 0
    
    //微博 创建 时间
    var created_at: String?
    
    //微博信息内容
    var text: String?
    
    //微博来源
    var source : String? {
        didSet{
             //<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
            let startRange = source?.rangeOfString("\">")
            let endRange = source?.rangeOfString("</a")
            
            if let range1 = startRange, range2 = endRange {
                let range = range1.endIndex..<range2.startIndex
                sourceText = source?.substringWithRange(range)
            }
        }
    }
    
    var sourceText: String?
    
    //用户模型属性
    var user: User?
    
    //转发微博模型  
    //如果是原创微博 retweeted_status
    var retweeted_status :Status?
    
    //配置视图数组的属性  数组 永远都不可能为nil 服务器在没有配图的情况下依然会返回一个空数组 而非 null 对象
    var pic_urls:[[String : String]]? {
        didSet{
            guard let urls = pic_urls else {
                return
            }   
            //遍历urls
            imageURLs = [NSURL]()
            for item in urls {
                let urlString = item["thumbnail_pic"]
                
                let url = NSURL(string: urlString!)!
                //将url对象添加到数组中
                imageURLs?.append(url)
            }
        }
    }
    
    var imageURLs:[NSURL]?
    
    //计算在下载单张图片的时候该下载谁的图片
    //被转发的原创微博中如果有图片  转发微博中就一定不会看到图片
    var pictureURLs: [NSURL]? {
        if retweeted_status != nil {
            //转发微博
            return retweeted_status?.imageURLs
        }
        return imageURLs
    }
    
    
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            //给user属性初始化
            //将AnyObject转换为字典对象
            if let dict = value as? [String : AnyObject] {
                //对 user 做字典转模型的操作
                user = User(dict: dict)
                return
            }
        }
        if key == "retweeted_status" {
            if let dict = value as? [String : AnyObject] {
                //对 retweeted_status 做字典转模型的操作
                retweeted_status = Status(dict: dict)
                return
            }
        }
        
        //很重要的一步  调用super
        super.setValue(value, forKey: key)
    }
    
    //过滤
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
}
